import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { useTheme } from '@/hooks/useTheme';
import { toast } from 'sonner';

// 定义配置选项的类型
export interface QRCodeConfig {
  roundedCorners: number;
  backgroundColor: string;
  patternColor: string;
  errorCorrectionLevel: 'L' | 'M' | 'Q' | 'H';
  logoUrl: string;
  logoSize: number;
  logoRoundedCorners: number;
  size: number; // 二维码尺寸，单位像素
  // 用于存储上传的文件信息
  uploadedFile?: File;
}

// 定义上传图片历史记录的类型
interface UploadedImage {
  id: string;
  dataUrl: string;
  name: string;
  timestamp: number;
}

interface QRCodeConfigPanelProps {
  config: QRCodeConfig;
  onConfigChange: (config: QRCodeConfig) => void;
}

export const QRCodeConfigPanel: React.FC<QRCodeConfigPanelProps> = ({ config, onConfigChange }) => {
  const { isDark } = useTheme();
  const [localConfig, setLocalConfig] = useState(config);
  // 存储用户上传的图片历史记录
  const [uploadedImages, setUploadedImages] = useState<UploadedImage[]>([]);
  
  const STORAGE_KEY = 'qrcode_generator_uploaded_images';
  const MAX_HISTORY_COUNT = 10;

  // 当外部配置变化时，更新本地配置
  useEffect(() => {
    setLocalConfig(config);
  }, [config]);

  // 从localStorage加载上传图片历史记录
  useEffect(() => {
    try {
      const savedImages = localStorage.getItem(STORAGE_KEY);
      if (savedImages) {
        const parsedImages: UploadedImage[] = JSON.parse(savedImages);
        setUploadedImages(parsedImages);
      }
    } catch (error) {
      console.error('加载上传图片历史记录失败:', error);
    }
  }, []);

  // 保存上传图片历史记录到localStorage
  const saveUploadedImages = (images: UploadedImage[]) => {
    try {
      // 确保总是保存一个有效的数组，避免空数组问题
      const validImages = images.filter(img => img && img.dataUrl);
      localStorage.setItem(STORAGE_KEY, JSON.stringify(validImages));
      setUploadedImages(validImages);
    } catch (error) {
      console.error('保存上传图片历史记录失败:', error);
      toast.error('保存图片历史记录失败');
    }
  };

  // 更新单个配置项
  const handleConfigChange = (key: keyof QRCodeConfig, value: any) => {
    const newConfig = { ...localConfig, [key]: value };
    setLocalConfig(newConfig);
    onConfigChange(newConfig);
  };

  // 添加新上传的图片到历史记录
  const addImageToHistory = (dataUrl: string, fileName: string) => {
    try {
      // 检查图片是否已存在于历史记录中（通过数据URL的前100个字符进行简单比较）
      const isDuplicate = uploadedImages.some(
        image => image.dataUrl.substring(0, 100) === dataUrl.substring(0, 100)
      );
      
      if (isDuplicate) {
        return; // 如果图片已存在，则不重复添加
      }
      
      // 创建新的图片记录
      const newImage: UploadedImage = {
        id: Date.now().toString(),
        dataUrl,
        name: fileName || '上传图片',
        timestamp: Date.now()
      };
      
      // 添加新图片并限制历史记录数量为10个
      const updatedImages = [newImage, ...uploadedImages].slice(0, MAX_HISTORY_COUNT);
      
      // 保存更新后的历史记录
      saveUploadedImages(updatedImages);
      
    } catch (error) {
      console.error('添加图片到历史记录失败:', error);
    }
  };

  // 默认示例logo选项
  const defaultLogoOptions = [
    { name: '无logo', url: '' },
    { name: '示例1', url: 'https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=minimal%20logo%20design%20white%20background&sign=7306a40abe2c1a0173ee3267fd9c1bc7' },
    { name: '示例2', url: 'https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=creative%20logo%20minimalist%20design&sign=48c0909eb400371f1410d712982f9e0a' },
    { name: '示例3', url: 'https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=simple%20icon%20logo%20design&sign=bc51d2218198bc447ae2a629f9156626' }
  ];

  // 默认颜色选项
  const defaultColorOptions = [
    { name: '黑色', value: '#000000' },
    { name: '深蓝色', value: '#1E40AF' },
    { name: '深绿色', value: '#166534' },
    { name: '红色', value: '#B91C1C' },
    { name: '紫色', value: '#6D28D9' }
  ];

  // 默认背景色选项
  const defaultBgColorOptions = [
    { name: '白色', value: '#FFFFFF' },
    { name: '浅灰色', value: '#F3F4F6' },
    { name: '浅蓝色', value: '#DBEAFE' },
    { name: '浅绿色', value: '#DCFCE7' }
  ];

  return (
    <motion.div
      initial={{ opacity: 0, y: 10 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.3 }}
      className={`mt-6 w-full p-5 rounded-xl ${isDark ? 'bg-gray-800' : 'bg-white'} shadow-md transition-colors duration-300`}
    >
      <h3 className="text-lg font-medium mb-4 flex items-center gap-2">
        <i className="fa-sliders text-blue-500"></i>
        样式配置
      </h3>
      
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {/* 图片尺寸 */}
        <div>
          <label className={`block text-sm font-medium mb-2 ${isDark ? 'text-gray-300' : 'text-gray-600'}`}>
            图片尺寸 ({localConfig.size}px)
          </label>
            <input
              type="range"
              min="128"
              max="512"
              step="1"
              value={localConfig.size}
              onChange={(e) => handleConfigChange('size', parseInt(e.target.value))}
              className={`w-full h-2 rounded-lg appearance-none cursor-pointer ${
                isDark ? 'bg-gray-700 accent-blue-500' : 'bg-gray-200 accent-blue-500'
              }`}
            />
          <p className={`text-xs mt-1 ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>
            调整二维码图片的整体尺寸
          </p>
        </div>

        {/* 圆角设置 */}
        <div>
          <label className={`block text-sm font-medium mb-2 ${isDark ? 'text-gray-300' : 'text-gray-600'}`}>
            圆角大小 ({localConfig.roundedCorners}%)
          </label>
          <input
            type="range"
            min="0"
            max="50"
            value={localConfig.roundedCorners}
            onChange={(e) => handleConfigChange('roundedCorners', parseInt(e.target.value))}
            className={`w-full h-2 rounded-lg appearance-none cursor-pointer ${
              isDark ? 'bg-gray-700 accent-blue-500' : 'bg-gray-200 accent-blue-500'
            }`}
          />
          <p className={`text-xs mt-1 ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>
            调整二维码图片的圆角程度
          </p>
        </div>

        {/* 图案颜色 */}
        <div>
          <label className={`block text-sm font-medium mb-2 ${isDark ? 'text-gray-300' : 'text-gray-600'}`}>
            图案颜色
          </label>
          <div className="flex gap-2 flex-wrap">
            {defaultColorOptions.map((color) => (
              <button
                key={color.value}
                onClick={() => handleConfigChange('patternColor', color.value)}
                className={`w-8 h-8 rounded-full transition-transform ${
                  localConfig.patternColor === color.value ? 'ring-2 ring-blue-500 scale-110' : ''
                }`}
                style={{ backgroundColor: color.value }}
                title={color.name}
              />
            ))}
            <input
              type="color"
              value={localConfig.patternColor}
              onChange={(e) => handleConfigChange('patternColor', e.target.value)}
              className="w-8 h-8 rounded-full overflow-hidden p-0 border-0 cursor-pointer"
            />
          </div>
        </div>

        {/* 背景颜色 */}
        <div>
          <label className={`block text-sm font-medium mb-2 ${isDark ? 'text-gray-300' : 'text-gray-600'}`}>
            背景颜色
          </label>
          <div className="flex gap-2 flex-wrap">
            {defaultBgColorOptions.map((color) => (
              <button
                key={color.value}
                onClick={() => handleConfigChange('backgroundColor', color.value)}
                className={`w-8 h-8 rounded-full transition-transform ${
                  localConfig.backgroundColor === color.value ? 'ring-2 ring-blue-500 scale-110' : ''
                }`}
                style={{ backgroundColor: color.value }}
                title={color.name}
              />
            ))}
            <input
              type="color"
              value={localConfig.backgroundColor}
              onChange={(e) => handleConfigChange('backgroundColor', e.target.value)}
              className="w-8 h-8 rounded-full overflow-hidden p-0 border-0 cursor-pointer"
            />
          </div>
        </div>

        {/* 容错率 */}
        <div>
          <label className={`block text-sm font-medium mb-2 ${isDark ? 'text-gray-300' : 'text-gray-600'}`}>
            容错率
          </label>
          <select
            value={localConfig.errorCorrectionLevel}
            onChange={(e) => handleConfigChange('errorCorrectionLevel', e.target.value as 'L' | 'M' | 'Q' | 'H')}
            className={`w-full p-2 rounded-lg border ${
              isDark 
                ? 'bg-gray-700 border-gray-600 text-white' 
                : 'bg-gray-50 border-gray-200 text-gray-800'
            }`}
          >
            <option value="L">低 (7%)</option>
            <option value="M">中 (15%)</option>
            <option value="Q">较高 (25%)</option>
            <option value="H">高 (30%)</option>
          </select>
        </div>

        {/* 中间Logo */}
        <div className="md:col-span-2">
          <label className={`block text-sm font-medium mb-2 ${isDark ? 'text-gray-300' : 'text-gray-600'}`}>
            中间Logo
          </label>
          <div className="flex gap-2 flex-wrap">
            {defaultLogoOptions.map((option) => (
              <button
                key={option.url}
                onClick={() => handleConfigChange('logoUrl', option.url)}
                className={`flex-shrink-0 flex flex-col items-center ${
                  localConfig.logoUrl === option.url 
                    ? 'ring-2 ring-blue-500 rounded-lg p-1' 
                    : 'p-1'
                }`}
              >
                {option.url ? (
                  <div className="w-14 h-14 rounded-lg overflow-hidden bg-gray-100 flex items-center justify-center">
                    <img 
                      src={option.url} 
                      alt={option.name} 
                      className="w-full h-full object-contain"
                      crossOrigin="anonymous"
                    />
                  </div>
                ) : (
                  <div className="w-14 h-14 rounded-lg bg-gray-200 flex items-center justify-center text-gray-500">
                    <i className="fa-ban text-xl"></i>
                  </div>
                )}
                <span className="text-xs mt-1">{option.name}</span>
               </button>
             ))}
            
            {/* 显示用户上传的图片历史记录 */}
            {uploadedImages.length > 0 && (
              <>
                <div className="w-full mt-2 mb-1 flex items-center justify-between">
                  <p className={`text-xs font-medium ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>
                    最近上传的图片
                  </p>
                    <button
                     onClick={() => {
                       if (confirm('确定要清除所有本地上传的图片吗？\n如果当前已选中本地图片，则会保留选中的图片。')) {
                         try {
                           // 检查当前选中的logo是否是本地上传的图片(Data URL)
                           const isSelectedLocalImage = localConfig.logoUrl.startsWith('data:image/');
                           
                           if (isSelectedLocalImage) {
                             // 找到当前选中的图片在历史记录中的索引
                             const selectedImageIndex = uploadedImages.findIndex(
                               image => image.dataUrl === localConfig.logoUrl
                             );
                             
                             if (selectedImageIndex !== -1) {
                               // 只保留当前选中的图片
                               const remainingImages = [uploadedImages[selectedImageIndex]];
                               saveUploadedImages(remainingImages);
                               toast.success('已保留当前选中的图片，清除了其他所有图片');
                             } else {
                               // 如果在历史记录中找不到当前选中的图片，则清除所有
                               // 使用saveUploadedImages确保状态和localStorage同步
                               saveUploadedImages([]);
                               toast.success('所有本地上传的图片已清除');
                             }
                           } else {
                             // 如果当前没有选中本地图片，则清除所有
                             // 使用saveUploadedImages确保状态和localStorage同步
                             saveUploadedImages([]);
                             toast.success('所有本地上传的图片已清除');
                           }
                         } catch (error) {
                           console.error('清除图片历史记录失败:', error);
                           toast.error('清除图片历史记录失败');
                         }
                       }
                     }}
                    className={`text-xs flex items-center gap-1 ${
                      isDark ? 'text-red-400 hover:text-red-300' : 'text-red-500 hover:text-red-600'
                    }`}
                  >
                    <i className="fa-trash-can"></i>
                    一键清除
                  </button>
                </div>
                {uploadedImages.map((image) => (
                  <button
                    key={image.id}
                    onClick={() => handleConfigChange('logoUrl', image.dataUrl)}
                    className={`flex-shrink-0 flex flex-col items-center ${
                      localConfig.logoUrl === image.dataUrl 
                        ? 'ring-2 ring-blue-500 rounded-lg p-1' 
                        : 'p-1'
                    }`}
                    title={image.name}
                  >
                    <div className="w-14 h-14 rounded-lg overflow-hidden bg-gray-100 flex items-center justify-center relative">
                      <img 
                        src={image.dataUrl} 
                        alt={image.name} 
                        className="w-full h-full object-contain"
                      />
                      <div className="absolute bottom-1 right-1 w-2 h-2 rounded-full bg-blue-500"></div>
                    </div>
                    <span className="text-xs mt-1 truncate max-w-[50px] text-center">{image.name}</span>
                  </button>
                ))}
              </>
            )}
            
            <div className="flex-1 min-w-[140px]">
              <input
                type="text"
                placeholder="自定义logo URL"
                value={localConfig.logoUrl}
                onChange={(e) => handleConfigChange('logoUrl', e.target.value)}
                className={`w-full p-2 rounded-lg border ${
                  isDark 
                    ? 'bg-gray-700 border-gray-600 text-white placeholder-gray-400' 
                    : 'bg-gray-50 border-gray-200 text-gray-800 placeholder-gray-400'
                }`}
              />
            </div>
            
            <div className="w-full mt-2">
              <button
                onClick={() => document.getElementById('logo-upload')?.click()}
                className={`inline-flex items-center gap-2 px-4 py-2 rounded-lg ${
                  isDark 
                    ? 'bg-gray-700 hover:bg-gray-600 text-white' 
                    : 'bg-gray-100 hover:bg-gray-200 text-gray-800'
                } transition-colors`}
              >
                <i className="fa-regular fa-image"></i>
                上传本地图片
              </button>
              <input
                type="file"
                id="logo-upload"
                accept="image/*"
                className="hidden"
                onChange={(e) => {
                  const file = e.target.files?.[0];
                  if (file) {
                    // 检查文件大小不超过2MB
                    if (file.size > 2 * 1024 * 1024) {
                      alert('图片文件大小不能超过2MB');
                      return;
                    }
                    
                    const reader = new FileReader();
                    reader.onload = (event) => {
                      const dataUrl = event.target?.result as string;
                      // 直接更新logoUrl，确保实时预览和下载一致
                      handleConfigChange('logoUrl', dataUrl);
                      handleConfigChange('uploadedFile', file);
                      
                      // 将图片添加到历史记录中
                      addImageToHistory(dataUrl, file.name);
                      
                      toast.success('图片上传成功');
                      console.log('文件上传成功，生成Data URL');
                    };
                    reader.onerror = () => {
                      alert('图片读取失败，请重新选择文件');
                      console.error('文件读取错误');
                    };
                    reader.readAsDataURL(file);
                  }
                }}
              />
            </div>
          </div>
        </div>

        {/* Logo大小 */}
        <div>
          <label className={`block text-sm font-medium mb-2 ${isDark ? 'text-gray-300' : 'text-gray-600'}`}>
            Logo大小 ({localConfig.logoSize}%)
          </label>
          <input
            type="range"
            min="10"
            max="35"
            value={localConfig.logoSize}
            onChange={(e) => handleConfigChange('logoSize', parseInt(e.target.value))}
            className={`w-full h-2 rounded-lg appearance-none cursor-pointer ${
              isDark ? 'bg-gray-700 accent-blue-500' : 'bg-gray-200 accent-blue-500'
            }`}
            disabled={!localConfig.logoUrl}
          />
          <p className={`text-xs mt-1 ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>
            {localConfig.logoUrl ? '' : '请先选择一个logo'}
          </p>
        </div>
        
        {/* Logo圆角 */}
        <div>
          <label className={`block text-sm font-medium mb-2 ${isDark ? 'text-gray-300' : 'text-gray-600'}`}>
            Logo圆角 ({localConfig.logoRoundedCorners}%)
          </label>
          <input
            type="range"
            min="0"
            max="50"
            value={localConfig.logoRoundedCorners}
            onChange={(e) => handleConfigChange('logoRoundedCorners', parseInt(e.target.value))}
            className={`w-full h-2 rounded-lg appearance-none cursor-pointer ${
              isDark ? 'bg-gray-700 accent-blue-500' : 'bg-gray-200 accent-blue-500'
            }`}
            disabled={!localConfig.logoUrl}
          />
          <p className={`text-xs mt-1 ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>
            {localConfig.logoUrl ? '' : '请先选择一个logo'}
          </p>
        </div>
      </div>
    </motion.div>
  );
}